import logging
import re
from urllib.parse import urlparse

from airflow.utils.state import State


class CommonUtil(object):
    log = logging.getLogger(__name__)

    PATTERN = re.compile("^\w+")

    @staticmethod
    def get_domain(url):
        u = urlparse(url)
        # if u.path.index("jobhistory"):

        return u.scheme + "://" + u.netloc

    @staticmethod
    def set_proxy_url(task_instance, spark_run_url, flink_run_url, end_url, app_url, proxy_url):
        try:
            state = task_instance.get("state", None)
            operator = task_instance.get("operator", None)
            if state and operator:
                hostname = task_instance.get("hostname", None)
                task_instance['application_id'] = hostname
                if operator == "FlinkSubmitOperator" or operator == "SparkSubmitOperator":
                    if state == State.RUNNING:
                        if operator == "SparkSubmitOperator":
                            app_proxy_url = spark_run_url.format(hostname)
                        else:
                            cluster_id = "{}-flink-cluster-rest:8081".format(task_instance.get("task_id"))
                            app_proxy_url = flink_run_url.format(cluster_id)
                        task_instance['app_proxy_url'] = app_proxy_url
                    elif state == State.FAILED or state == State.SUCCESS \
                            or state == State.UP_FOR_RETRY or state == State.UP_FOR_RESCHEDULE:
                        app_proxy_url = None
                        # app_proxy_url = end_url.format(hostname)
                        task_instance['app_proxy_url'] = app_proxy_url
                        task_instance['driver_proxy_url'] = app_proxy_url

                    # 下面代码获取 driver 日志的返回结果中的 amContainerLogs 打开不稳定
                    # if app_id:
                    #     real_app_url = app_url.format(app_id)
                    #     result = requests.get(real_app_url, timeout=3)
                    #     if result.status_code == 200:
                    #         app = result.json().get("app", None)
                    #         if app:
                    #             am_container_logs = app.get("amContainerLogs", None)
                    #             task_instance['driver_proxy_url'] = proxy_url.format(am_container_logs)
                    #             diagnostics = app.get("diagnostics", None)
                    #             task_instance['diagnostics'] = diagnostics
        except Exception as e:
            logging.error("resourcemanager connection error: %s", repr(e))
